<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>       
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="${_resources}/logo.png"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">                                            
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />  
<title>文档模板基本信息</title>
<style type="text/css">
.file{margin-top: 10px;}
</style>
</head>
<%@ include file="/WEB-INF/jsp/common/inc.jsp" %>
<script type="text/javascript" src="${_resources}jquery-ui/jquery-ui-1.10.4.custom.min.js"></script>
<link rel="stylesheet" href="${_resources}jquery-ui/jquery-ui-1.10.4.custom.min.css" />
<style type="text/css">
body{	
	overflow:hidden;
}
.jbinformation .jbxinxi_input{width:290px}
.file input{width:62px}
.ui-draggable .ui-dialog-titlebar{height: 29px;}
</style>
<script type="text/javascript">
$(function(){
    $.validationEngineLanguage.allRules.commonLetter = {
        "regex": /^[0-9a-zA-Z\_\-]+$/,
        "alertText": "* 由数字、英文、</br>-、下划组成"
    };


    $("input[type='file']").change( function() {
		var fileType =$("#textfield").val();
		$(".upload_text").text(fileType);
		$(".upload_text").attr("title",fileType);
		$(".upload_delete").click(function(){
			$(".upload_text").val("");
			$(".upload_text").text("");
			$("#textfield").val("");
			$(".upload_text").attr("title","");
			});
		});
	})
var beforeSrc ="";
function selectCreate(value){
	if(value=="newCreate"){
		var frame = $("#templatelist");
		var src  = $(frame).attr("src");
		beforeSrc=src;
		$(frame).attr("src","");
		setTimeout(function(){
			$("#popIframe").empty();	
			$("#popDiv").dialog({
				title:'新增适用范围',
				autoOpen: true,
				modal: true,	
				height: 300,
				width: 500,
				close:function(event,uri){
					showBeforeSection();
				}
			});	
			$("#popIframe").attr("width","100%");
			$("#popIframe").attr("height","95%");
			$("#popIframe").attr("src","${_baseUrl}/applicableScopeController/newApplicableScope?rand="+Math.random());
		},1500);	
	}
}
function getApplicationScope(){
	var path="${_baseUrl}/applicableScopeController/SelectAllApplicableScope";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,
		dataType:"json",    
		success: function (data) {   
			var jsonObj=eval("("+data.message+")");
			var options="";
			if(jsonObj.length>0){
				options+="<option>请选择</option>";
				$.each(jsonObj, function (i, item) {
					options+="<option value='"+item.scopeName+"'>"+item.scopeName+"</option>";
			 	});
			}
			//options+="<option value='newCreate'>新建适用范围</option>";
			$("#applicationScope").html(options);			
		}   
	}); 	
}

function getTemplateCode(fileName){
    var path="${_baseUrl}/KmGroupDocumentTemplateController/getTemplateCode";
    $.ajax({
        type: "POST",
        async: false,
        url:path,
        datatype: "json",
        data:{
            "docName":fileName
        },
        success: function (json) {
            if(json.code == "1"){
                $("#documentCode").val(json.data);
                $("#documentCode").attr("readonly",true);
                $("#isExistCode").val("1");
            }else{
                $("#isExistCode").val("");
                $("#documentCode").val("");
                $("#documentCode").attr("readonly",false);
            }
        }
    });
}

$(function(){
	$("#form").validationEngine({
		autoHidePrompt:true,//自动隐藏
		showOnMouseOver:true,//当鼠标移出时触发
		promptPosition:'bottomLeft',//提示信息的位置
		inlineValidation: true,//是否即时验证，false为提交表单时验证,默认true  
		failure : function() {
		    layer.message("验证失败，请检查");
			return false;  
		},//验证失败时调用的函数
		ajaxFormValidation: true,//开始AJAX验证
		success : function() {
		//	$("#addForm").submit();
		}//验证通过时调用的函数 
		//onAjaxFormComplete: ajaxValidationCallback
	});
	$("#textfield").change(function (){
        var path = $("#textfield").val();
        var pos1 = path.lastIndexOf('/');
        var pos2 = path.lastIndexOf('\\');
        var pos = Math.max(pos1, pos2);
        var fileName;
        if( pos<0 )
            fileName = path;
        else
            fileName = path.substring(pos+1); 
        fileName = fileName.substring(0,fileName.lastIndexOf("."));
     
        $("#documentTemplateName").val(fileName);
        if(judgeName()){
            getTemplateCode(fileName);
        }
       
    });
	selectTemplateSort1();
});
//删除刚才上传的模板数据
function del(){
	parent.closeWin();
}

function getTemplateCode(fileName){
    var path="${_baseUrl}/KmGroupDocumentTemplateController/getTemplateCode";
    $.ajax({
        type: "POST",
        async: false,
        url:path,
        datatype: "json",
        data:{
            "docName":fileName
        },
        success: function (json) {
            if(json.code == "1"){
                $("#documentCode").val(json.data);
                $("#documentCode").attr("readonly",true);
                $("#isExistCode").val("1");
            }else{
                $("#isExistCode").val("");
                $("#documentCode").val("");
                $("#documentCode").attr("readonly",false);
            }
        }
    });
}

function formSubmit(){
    // 判断上传文件格式是否为doc,docx,zip,rar
    if (judgeFileType()!=true){
        layer.msg(judgeFileType())
        return;
    }
	var formChecked = $('#form').validationEngine('validate');
	if(formChecked){
		var path="${_baseUrl}/KmGroupDocumentTemplateController/judgeDocumentName";
		var name = $("#documentTemplateName").val();
		var fileType =$("#textfield").val();
		var file = "";
		var type = "";
		if(fileType != null && fileType != ""){
			type = fileType.substring(fileType.lastIndexOf(".")+1);
			if(type == "zip"||"rar" == type){
				file = type;
			}else{
				if(!judgeName){
					return;
				}
			}
		}else{
	      	 layer.msg("请先上传模板");
	    	 return;
	    }
		
		var options = {
			dataType:"json",
			data : {
	  			fileType:file
	  		},
			success:function(json){			
					layer.msg(json.message,{offset:['35%','45%']},function(){
						parent.closeWin();
						parent.refreshTable();	
					});
					
			},
			error:function(json){
				layer.msg("系统错误,请联系管理员");
			}
		};
		
		if(type == "zip"||"rar" == type){
			if(formChecked){
				$('#form').ajaxSubmit(options);
				layer.msg('文档上传中,请稍后...', {icon: 16,time:0,shift:1});
			}	
			return;
		}
		
		if("${documentTemplate}" != null){
			if(name !=""){
				$.ajax({    
					type: "POST",    
					async: false,    
					url:path,
					data:{
						"docName":name,
						"id":$("#id").val()
					},
					dataType:"json",    
					success: function (json) { 
						if(json.code=="1"){
							layer.msg("模板名称已经存在",{offset:['15%','25%']});
							$("#documentTemplateName").val("");
						}else{
							if(formChecked){
								//加载层-风格2
								layer.confirm('正在上传数据,请稍后...',{icon: 16,shade: 0.3,
								success: function(layero){
						        	 var obj = $(".layui-layer"),oClose = $(".layui-layer-close");
									 str = "<iframe  frameborder=\"0\" scrolling=\"no\" style=\"position:absolute; background-color:transparent; width:100%; height:100%; top:0px; left:0px; z-index:-1;\"></iframe>";
									 obj.prepend(str);
									 oClose.click(function(){
										    var oShade = $("#templatelist").contents().find("#shade");
											oShade.css({'width':'0','height':'0'});
											$("#popDivs").css("height","100%");
								     }); 
								     $(".layui-layer").css("background-color","#f0efef");
										$(".layui-layer-content").css("text-align","center");
										$(".layui-layer-setwin").css("display","none");
										$(".layui-layer-btn").css("display","none");
										$(".layui-layer-title").css("display","none");
										$(".layui-layer-content").css("height","70px");
						        }});
								$("#submit").attr("onClick","");
								$('#form').ajaxSubmit(options);
							}
						}
					}   
				});
			}
		}else{
			if(name !=""){
				$.ajax({    
					type: "POST",    
					async: false,    
					url:path,
					data:{
						"docName":name,
					},
					dataType:"json",    
					success: function (json) { 
						if(json.code=="1"){
							layer.msg("模板名称已经存在",{offset:['15%','25%']});
						}else{
							if(formChecked){
								//加载层-风格2
								layer.confirm('正在上传数据,请稍后...',{icon: 16,shade: 0.3,
				success: function(layero){
		        	 var obj = $(".layui-layer"),oClose = $(".layui-layer-close");
					 str = "<iframe  frameborder=\"0\" scrolling=\"no\" style=\"position:absolute; background-color:transparent; width:100%; height:100%; top:0px; left:0px; z-index:-1;\"></iframe>";
					 obj.prepend(str);
					 oClose.click(function(){
						    var oShade = $("#templatelist").contents().find("#shade");
							oShade.css({'width':'0','height':'0'});
							$("#popDivs").css("height","100%");
				     }); 
				     $(".layui-layer").css("background-color","#f0efef");
						$(".layui-layer-content").css("text-align","center");
						$(".layui-layer-setwin").css("display","none");
						$(".layui-layer-btn").css("display","none");
						$(".layui-layer-title").css("display","none");
						$(".layui-layer-content").css("height","70px");
		        }});
								$("#submit").attr("onClick","");	
								$('#form').ajaxSubmit(options);
							}
						}
					}   
				});
			}
		}	
	}
}



//文档分类管理
function defineTemplateSort(){
	var frame = $("#templatelist");
	var src  = $(frame).attr("src");
	beforeSrc=src;
	$(frame).attr("src","");
	setTimeout(function(){
		$("#popIframe").empty();	
		$("#popDiv").dialog({
			title:'文档模板分类管理',
			autoOpen: true,
			modal: true,	
			height: 500,
			position:'center',
			width: 500,
			close:function(event,uri){
				showBeforeSection();
			}
			
		});	
		$("#popIframe").attr("width","100%");
		$("#popIframe").attr("height","95%");
		$("#popIframe").attr("src","${_baseUrl}/templateSortController/showTemplateSort?rand="+Math.random());
	},1500);
}
//选择文档模板分类
function selectTemplateSort(){
	var frame = $("#templatelist");
	var src  = $(frame).attr("src");
	beforeSrc=src;
	$(frame).attr("src","");
	setTimeout(function(){	
		$("#popIframe").empty();	
		$("#popDiv").dialog({
			title:'文档模板分类管理',
			autoOpen: true,
			modal: true,
			position:'center',
			height: 380,
			width:500,
			close:function(event,uri){
				showBeforeSection();
			}
		});	
		$("#popIframe").attr("width","100%");
		$("#popIframe").attr("height","95%");
		$("#popIframe").attr("src","${_baseUrl}/templateSortController/setTemplateSort?rand="+Math.random());
	},1500);	
}

//选择文档模板分类
function selectTemplateSort1(value){
	var path ="${_baseUrl}/templateSortController/setTemplateSort1";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,   
		dataType:"json",    
		success: function (data) {  
			    var json = data.message;
				var jsonObj=eval("("+json+")");
				var options="";
				options+="<option>请选择</option>";
				if(jsonObj.length>0){
					var documentType="${documentTemplate.documentType}";
					$.each(jsonObj, function (i, item) {
						if(documentType.indexOf(item.id)!=-1){
							options+="<option value='"+item.id+"' selected='selected' >"+item.sortName+"</option>";
                            // 使用隐藏域保存模板类型id，故这里在初始化模板类型下拉框时，也应同步初始化隐藏域
                            document.getElementById("documentType").value = item.id;
						}else{
							options+="<option value='"+item.id+"'>"+item.sortName+"</option>";
						}
				 	});
				}
				$("#documentTypeName").html(options);	
		}   
	}); 
}

function setDocumentTypeValue(){
	var doucumentType = $("#documentTypeName").find("option:selected").val();
	$("#documentType").val(doucumentType);
}

/* 关闭弹出框 */
function closeWin(){
	$("#popDiv").dialog('close');
}

//验证活动类型
function checkSelectOut(){	
	var select = $("select[name='styleOutTemplate']");
	var options = $(select).find("option");
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			var value = $(options[i]).val();
			if(value=="请选择"){
				return "请选择样式模板名称";
			}else{
				return true;
			}
		}
	}
	
}
//验证活动名称
function checkSelectSet(){	
	var select = $("select[name='styleSetTemplate']");
	var options = $(select).find("option");
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			var value = $(options[i]).val();
			if(value=="请选择"){
				return "请选择样式模板名称";
			}else{
				return true;
			}
		}
	}
	
}

//验证适用范围
function checkSelectScope(){	
	var select = $("select[name='applicationScope']");
	var options = $(select).find("option");
	var value="";
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			value = $(options[i]).val();
			
		}
	}

	if(value=="请选择"){
		return "请选择适用范围";
	}else{
		return true;
	}
}

//验证模板分类
function checkTemplcateSort(){	
	var select = $("select[name='documentTypeName']");
	var options = $(select).find("option");
	var value="";
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			value = $(options[i]).val();
			
		}
	}

	if(value=="请选择"){
		return "请选择模板分类";
	}else{
		return true;
	}
}

var activeName = null;
var activeType = null;

function showBeforeSection(){
	var frame = $("#templatelist");
	if(beforeSrc!=""){
		$(frame).attr("src",beforeSrc);
	}
}
//根据活动类型，切换活动名称
function addName(value){
	var path ="${_baseUrl}/activeName/getActiveName";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,   
		data:{
			"activeType":value      
		},    
		dataType:"json",    
		success: function (json) {   
			if(json.code=="1"){
				var jsonObj=eval("("+json.message+")");
				var options="";
				options+="<option>请选择</option>";
				if(jsonObj.length>0){
					
					$.each(jsonObj, function (i, item) {
						options+="<option value='"+item.id+"'>"+item.activeName+"</option>";
				 	});
				}
				$("#actionName").html(options);	
			}
		}   
	}); 
}

document.onkeydown=function(event){ 
	e = event ? event :(window.event ? window.event : null); 
	if(e.keyCode==13){ 
		return false; 
	} 
}

function judgeName(){
	var flag = true;
    var path="${_baseUrl}/KmGroupDocumentTemplateController/judgeDocumentName";
    var name = $("#documentTemplateName").val();
    var type = $("#type").val();
    if(name !=""){
        $.ajax({    
            type: "POST",    
            async: false,    
            url:path,
            data:{
                "docName":name,
                "type":type,
                "id":$("#id").val()
            },
            dataType:"json",    
            success: function (json) {   
                if(json.code=="1"){
                    layer.msg("模板名称已经存在");
                    $("#documentTemplateName").val("");
                    flag = false;
                };
            }   
        });
    }
    return flag;
}
function judge_enter(){
    if(window.event.keyCode==13){
        event.returnValue = false;//阻止刷新页面
  }
}
function judgeFileType(){
	var id = "${documentTemplate.id}";
    var fileType =$("#textfield").val();
    var typeMark =  fileType.substring(fileType.length-4,fileType.length);

    if(id == null || id == ""){
    	if(typeMark ==".rar"|| typeMark == ".zip" || typeMark == ".doc"||typeMark ==".DOC"||(typeMark =="docx" &&fileType.indexOf("."))||(typeMark=="DOCX"&&fileType.indexOf("."))){
    	   	return true;
    	}else{
    	   	return "请选择doc,docx,rar或zip格式文件!";
    	};	 
    }else{
    	if(typeMark == ".doc"||typeMark ==".DOC"||(typeMark =="docx" &&fileType.indexOf("."))||(typeMark=="DOCX"&&fileType.indexOf("."))){
    	   	return true;
    	}else{
    	   	return "请选择doc或docx文件！";
    	};
    };
}
</script>
<body>
<form action = "${_baseUrl}/KmGroupDocumentTemplateController/documentTemplateInfo" method="post" id="form" enctype="multipart/form-data">
<input type="hidden" name="token" value="${token}" />
<input type="hidden" value="${documentTemplate.id}" name="id" id="id"/>
 <div class="jbinformation wdmubansr shcuan_t">
        <table class="table table-bordered submenu_table">
            <tr >
                <td height="50" width="15%" align="center">
                  <c:if test="${empty documentTemplate.id}">
                                    上传文档
                  </c:if>              
                  <c:if test="${not empty documentTemplate.id }">
                                    新文档
                  </c:if>              
                </td>
                <td width="35%">
			        <div class="upload">
			        	<input class="upload_input" type="file" class="nav_input validate[required,funcCall[judgeFileType]" name=multipartfile id="textfield" >
			        	<div class="upload_text"></div>
			        	<div class="upload_text_a"></div>
			        	<a class="upload_btn" href="javascript:;">上传</a>
			        	<a class="upload_delete" href="javascript:;"></a>
			        </div>
		        </td>
                <td height="50" width="15%" align="center"  name="documentTemplateName"><span style="color:#f00">*</span> 文档模板名称</td>
                <td width="35%" valign="middle">
                    <div>
                        <input type="text"  name="documentTemplateName" id="documentTemplateName"   value="${documentTemplate.documentTemplateName}" onkeypress="judge_enter();" onkeydown="judge_enter();" class="nav_input validate[maxSize[50] required]">
                    </div>
                </td>
            </tr>
            <tr >
                <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 模板分类</td>
                <td width="35%" valign="middle">
	                <div>
		                <select name ="documentTypeName" id="documentTypeName" class="func_select validate[required,funcCall[checkTemplcateSort]]" style="width:100%;margin:0;" onchange="setDocumentTypeValue()">
		                </select>
		                <input type="hidden" name ="documentType" id="documentType">
	                </div>
	                 
                </td>
				<td height="50" width="15%" align="center"><span style="color:#f00">*</span> 文档标识</td>
                <td width="35%" valign="middle">
	                <div>
		                <input type="text"  name=documentCode  id="documentCode"  value="${documentTemplate.documentCode}"  class="nav_input validate[maxSize[50] required]">
                        <input type="hidden" name ="isExistCode" id="isExistCode" value="${documentTemplate.documentCode}">
	                </div>
                </td>
          </tr>
          <tr >
                <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 适用范围</td>
                <td width="35%" valign="middle">
                    <div>
	                    <select class="func_select  validate[required,funcCall[checkSelectScope]]" name="applicationScope" id="applicationScope" style="width:100%;margin:0;"  onchange="selectCreate(this.options[this.options.selectedIndex].value)">
	                    <option >请选择</option>
	                    <c:forEach items="${listApplicableScope}" var="applicableScope">
	                       <option value="${applicableScope.id }" <c:if test="${documentTemplate.applicationScope eq applicableScope.id}">selected="selected"</c:if>>${applicableScope.application }</option>
	                    </c:forEach>
	                    </select>
                    </div>
                </td>
                <td height="50" width="15%" align="center">活动类型</td>
	            <td width="35%" valign="middle">
	                <div>
			            <select   name ="activeType" id="activeType" class="func_select" onchange="addName(this.options[this.options.selectedIndex].value)" style="width:100%;margin:0;">
			              <option value="">请选择</option>
			              <c:forEach items="${listActiveType}" var="activeType">
							<option value="${activeType.id}" <c:if test="${documentTemplate.activeType eq activeType.id}">selected="selected"</c:if> >${activeType.activeType }</option>
						</c:forEach>
			            </select>
	                </div>
	            </td>
          </tr>
          <tr align="center" valign="middle" >
            <td height="50" width="15%" align="center">活动名称</td>
            <td width="35%" valign="middle">
	            <div>
	              <select class="func_select"  name ="actionName" id="actionName" style="width:100%;margin:0;">
	                <option value="">请选择</option>
	                <c:forEach items="${activeNameList}" var="a">
	                   <option value="${a.id}"   <c:if test="${documentTemplate.actionName eq a.id}">selected="selected"</c:if> >${a.activeName}</option>
	                </c:forEach>
	              </select>
	            </div>
            </td>
          </tr>
        </table>
        <c:if test="${empty documentTemplate.id}">
        	<span style="font-size: 13px;margin-top:0px ;margin-left:1% ;color: #4F81F4;">批量上传说明：目前仅支持ZIP,RAR4.0压缩文件!</span> 
        </c:if>	       	
</div>
    </div>
    <div class="permission_an mubanclass_an ma">
    	<shiro:hasPermission name="KmGroupDocumentTemplateController:documentTemplateInfo">
             <a href="javascript:void(0);" id="submit" class=" per_baocun" onclick="formSubmit();">${empty documentTemplate.id ? '加入模板库' : '保存' }</a>
	   </shiro:hasPermission>
        <shiro:hasPermission name="KmGroupDocumentTemplateController:close1">
            <a href="javascript:void(0);" onclick="del();" id="cancel">取消</a>   <!-- 改为取消按钮  -->
        </shiro:hasPermission>
    </div>
  
  <input type="hidden" id="source" name="source" value="${source}">
  <div id="popDiv" style="position:relative; z-index:1000; display: none;">
		<iframe id="popIframe" border="0" frameborder="no"></iframe>
	</div>  
	 
	 
</form>
</body>
<script type="text/javascript">

</script>
</html>